from pymongo import MongoClient
client = MongoClient(port=27017)
db=client['tiktok']
# labels={}
# with open('E:\\data_pi\\labels_d1.txt', 'r', encoding='utf-8',
#           newline='\n') as filename_input:
#     for line in filename_input:
#         l=line.strip().split('\t')
#         labels[l[0]]=[l[1],l[2]]
# collist=['makeitvogue','LGBTQHistory','wip','haventseen','holidayvibes','SkateLife','ootd','bekind','personalfinance','cozyathome','gamenight','happyholidays','ProblemSolved','veteransday','RoomTour','meleaving','yellow']
#
# for col in collist:
#     for obj in db[col].find():
#         if obj['_id'] in labels:
#             db[col].update_one({'_id': obj['_id']}, {'$set':{'video_feature.label':{'labelA':labels[obj['_id']][0],'labelB':labels[obj['_id']][1]}}})
#         else:
#             print(obj['_id'],'not in labels')
#

import csv
labels={}
idlist=[]
ht=['ComingOfAge', 'falldiy', 'gaminglife', 'interiordesign', 'oneyourthere', 'sfxmakeup', 'tiktokfood', 'worldseries', 'halloweenishere', 'meleaving', 'yellow', 'yougotthis', 'mycostume', 'animation', 'youwantmore', 'halloweenlook', 'mypfp', 'nativefamily', 'welldone', 'happyhalloween', 'OhNo', 'holidaytiktok', 'rnbvibes', 'carsoftiktok', 'homeoffice', 'myrecommendation', 'fallfashion', 'familyimpression', 'myhobby', 'neonshadow', 'fanedit', 'stemlife', 'motivationmonday', 'wip', 'veteransday', 'holidaycountdown', 'whereilive', 'bekind', 'onhold', 'diwali', 'WeekendVibes', 'bakingszn', 'RoomTour', 'foodtiktok', 'growupwithme', 'holidaysourway', 'tabletop', 'nbadraft', 'recordsday', 'ourtype', 'nonuancenovember', 'artmas', 'gamingsetup', 'theatrekids', 'needtoknow', 'whenwewereyounger', 'graphicdesign', 'inkdrawing', 'fallguysmoments', 'familyrecipe', 'onlinedating', 'watchmegrow', 'givingthanks', 'readysetshop', 'diceroll', 'smallbusiness', 'holidayvibes', 'coldweather', 'givingszn', 'happyholidays', 'homecooked', 'easydiy', 'wildanimals', 'holidaymusic', 'howbizarre', 'selfimprovement', 'ImAGhost', 'personalfinance', 'housetour', 'thinkingabout', 'holidaycrafts', 'happyhanukkah', 'RatatouilleMusical', 'catchphrases', 'ootd', 'comfortfood', 'holidaydecor', 'raisedby', 'goodmorning', 'makeitvogue', 'festivefashion', 'gamenight', 'artmas', 'haventseen', 'planttiktok', 'productivity', 'lovestory', 'wishlist', 'hellowinter', 'YearOnTikTok', 'nbaisback', 'perfectgifts', 'holidaytreats', 'wrappinggifts', 'feliznavidad', 'timewarpjump', 'christmas2020', 'MyHaul', 'cozyathome', 'myhaul', 'winterfit', 'withouttellingme', 'hyperfixated', 'whatilearned',  'WordsOfWisdom',  'rareaesthetic', 'welcome2021', 'dailyvlog', 'easyrecipe', 'mystyle', 'Bye2020', 'myroutine', 'gamergoals', 'projectcar', 'homemade', 'inlove', 'GreenScreenScan', 'tortillatrend', 'NFLplayoffs', 'FitnessRoutine', 'IsThisAvailable', 'wee', 'weirdpets', 'fitnessroutine',  'moneytok', 'nflplayoffs', 'healthycooking', 'nhlfaceoff', 'groupchat', 'NHLFaceOff', 'winterfashion', 'skincare101', 'zodiacsign', 'homeimprovement', 'seashanty', 'cleantok', 'visionboard', '2021affirmations', 'mlkday', 'joblife', 'foodie', 'timewarpwaterfall', 'plantparent', 'WinterMagic', 'notaperfectperson', 'tiktoktutorial', 'cocinando', 'OlympicsCountdown', 'couplethings', 'clingypet', 'meditation101', 'winterbeautytips', 'tiktokdiy', 'typing', 'roundofapplause', 'xgamesmode', 'feelinggood', 'RoyalRumble', 'emophase', 'wintersports', 'makeblackhistory', 'relationshipstorytime', 'albumcover', 'stepbystep', 'fetapasta', 'womeninsports', 'healthyheart', 'imbusyrightnow', 'beautyhacks', 'tiktoktailgate', 'puppybowl', 'superbowllv', 'valentinesdiy', 'melaninmagic', 'coversforlovers', 'kissyourpet', 'womeninstem', 'lunarnewyear', 'perfectmatch', 'galentinesday', 'valentinesday', 'loveyourinsecurities', 'tiktokfashionmonth', 'blackcreatives', 'colddays', 'mifamilia', 'careeradvice', 'stopasianhate', 'perfectdrink', 'snowstorm', 'carhacks', 'homeproject', 'blackandproud', 'dramaticmoments', 'bakedoats', 'homecook', 'laughingduet', 'yoga101', 'somethingyoulearned', 'upcycling', 'fantheory', 'tiktokfitness', 'gamingtiktok', 'seitan', 'glasspainting', 'whenwomenwin', 'science101', 'thriftflip', 'Lifestyle', 'tiktokwildlifeday', 'dayandnight']
hts=[h.lower().replace('#','') for h in ht]
lowers={}
for col in db.list_collection_names():
    lowers[col.lower()]=col
ht=[]
for item in hts:
    if item not in ht:
        ht.append(item)

for c in range(len(ht)):
    if ht[c] in lowers.keys():
        ht[c]=lowers[ht[c]]
with open('D:\\Work\\Tool\\tiktok\\all\\infos_d7_r.tsv', 'r', encoding='utf-8', newline='\n') as filename_input:
    reader = csv.reader(filename_input, delimiter='\t')
    next(reader)
    i=0
    for line in reader:
        idlist.append(line[1])
        labels[idlist[i]]=[ht[int(line[0])-1]]
        i+=1
with open('C:\\Users\\Ziyue Luo\\Downloads\\newlabel.csv', 'r', encoding='utf-8', newline='\n') as filename_input:
    i=0
    reader = csv.reader(filename_input, delimiter=',')
    next(reader)
    for line in reader:
        labels[idlist[i]].extend([line[1],line[3],line[0],line[2]])
        i+=1

# with open('C:\\Users\\Ziyue Luo\\Downloads\\blable.csv', 'r', encoding='utf-8', newline='\n') as filename_input:
#     i=0
#     reader = csv.reader(filename_input, delimiter=',')
#     next(reader)
#     for line in reader:
#         labels[idlist[i]].append(line[0])
#         i+=1

# for col in db.list_collection_names():
#     print(col)
#     for obj in db[col].find():


newlabels=['2018vs2021', '90saesthetic', 'albumcover', 'amongus', 'aprilfools', 'arabtiktok', 'athletesoftiktok', 'autismawareness', 'bakedoats', 'baseballisback', 'beautyhack', 'beautyhacks', 'blackandproud', 'careeradvice', 'carhacks', 'cartiktok', 'cleaningtiktok', 'colddays', 'colorblast', 'competitivegaming', 'coversforlovers', 'crowdcheers', 'dailyvlog', 'dayandnight', 'defrosting', 'dinnerparty', 'diyprojects', 'doctorsoftiktok', 'dramaticmoments', 'earthday', 'easyrecipe', 'ecohacks', 'emophase', 'fantheory', 'feelinggood', 'feliznavidad', 'fetapasta', 'fitnesslife', 'foodie', 'foodontiktok']


for newht in newlabels:
    scss=0
    for obj in db[newht].find():
        if obj['_id'] in idlist:
            id=obj['_id']
            try:
                #db[col].update_one({'_id': obj['_id']}, {'$set':{'video_feature.label':{'labelA':labels[obj['_id']][0],'labelB':labels[obj['_id']][1]},'video_feature.residual':{'residualA':labels[obj['_id']][2],'residualB':labels[obj['_id']][3]}}})
                db[newht].update_one({'_id': id}, {
                    '$set': {'video_feature.label.labelA_n': labels[id][1], 'video_feature.label.labelB_n': labels[id][2],'video_feature.residual.residualA_n': labels[id][3],'video_feature.residual.residualB_n': labels[id][4]}})
                scss+=1
            except:
                print(id,'Error')
    print(newht,scss)